package com.sgcc.ln.pmos.common.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.sgcc.pmos.nativesdk.R;

import java.util.HashMap;

/**
 * @author Jcking
 * @time 2021-01-05 15:39
 */
public class LoadingDialogUtils {
    private static HashMap<String, Dialog> dialogs = new HashMap<>();

    public synchronized static Dialog showLoadingDialog(Activity activity) {
        if (!ActivityUtils.isActivityAlive(activity)) {
            return null;
        }
        return showLoadingDialog(activity, "");
    }

    /**
     * 显示加载对话框。
     * #21216 增加同步，防止多次创建。
     */
    public synchronized static Dialog showLoadingDialog(Activity activity, String msg) {
        return showLoadingDialog(activity, msg, true);
    }

    /**
     * 显示傻批加载对话框。
     * #21216 增加同步，防止多次创建。
     */
    public synchronized static Dialog showSpecialLoadingDialog(final Activity activity, String title, String content) {
        if (!ActivityUtils.isActivityAlive(activity)) {
            return null;
        }
        return showSpecialLoadingDialog(activity, title, content, true);
    }

    /**
     * 显示加载对话框。
     * #21216 增加同步，防止多次创建。
     */
    public synchronized static Dialog showLoadingDialog(final Activity activity, String msg, boolean isCancelable) {
        String key = getKey(activity);
        Dialog dialog = dialogs.get(key);
        if (dialog == null) {
            dialog = createLoadingDialog(activity, msg, isCancelable);
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    String key = getKey(activity);
                    dialogs.remove(key);
                }
            });
            dialogs.put(key, dialog);
        }
        try {
            if (!dialog.isShowing() && ActivityUtils.isActivityAlive(activity)) {
                dialog.show();
            }
        } catch (Exception e) {
        }
        return dialog;
    }

    /**
     * 显示加载对话框。
     * #21216 增加同步，防止多次创建。
     */
    public synchronized static Dialog showSpecialLoadingDialog(final Activity activity, String title, String content, boolean isCancelable) {
        String key = getKey(activity);
        Dialog dialog = dialogs.get(key);
        if (dialog == null) {
            dialog = createSpecialLoadingDialog(activity, title, content, isCancelable);
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    String key = getKey(activity);
                    dialogs.remove(key);
                }
            });
            dialogs.put(key, dialog);
        }
        try {
            if (!dialog.isShowing() && !activity.isFinishing() && !activity.isDestroyed()) {
                dialog.show();
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return dialog;
    }

    /**
     * 根据activity获取key
     */
    private static String getKey(Activity activity) {
        //java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
        if (null == activity) {
            return "activity is null";
        }
        return activity.toString();
    }

    /**
     * 生成对话框
     */
    private static Dialog createLoadingDialog(Activity activity, String msg, boolean isCancelable) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_loading, null);// 得到加载view
        Dialog loadingDialog = new Dialog(activity, R.style.circular_dialog);// 创建自定义样式dialog
        loadingDialog.setCancelable(isCancelable);
        loadingDialog.setCanceledOnTouchOutside(false); // 点击加载框以外的区域
        loadingDialog.setContentView(view, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        ImageView load_imageview = view.findViewById(R.id.load_imageview);
        TextView tipTextView = view.findViewById(R.id.text);
        if (TextUtils.isEmpty(msg)) {
            tipTextView.setVisibility(View.GONE);
            tipTextView.setText("");
        } else {
            tipTextView.setVisibility(View.VISIBLE);
            tipTextView.setText(msg);
        }
        AnimationDrawable animationDrawable = (AnimationDrawable) load_imageview.getBackground();
        animationDrawable.start();
        /* 将显示Dialog的方法封装在这里面 */
        Window window = loadingDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        return loadingDialog;
    }

    /**
     * 生成一个傻批Dialog
     */
    private static Dialog createSpecialLoadingDialog(Activity activity, String title, String content, boolean isCancelable) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_special_loading, null);// 得到加载view
        TextView tvTitle = view.findViewById(R.id.text_title);
        TextView tvContent = view.findViewById(R.id.text_content);
        tvTitle.setText(title);
        tvContent.setText(content);
        Dialog loadingDialog = new Dialog(activity, R.style.circular_dialog);// 创建自定义样式dialog
        loadingDialog.setCancelable(isCancelable); // 是否可以按“返回键”消失
        loadingDialog.setCanceledOnTouchOutside(false); // 点击加载框以外的区域
        loadingDialog.setContentView(view, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        ImageView load_imageview = view.findViewById(R.id.load_imageview);
        AnimationDrawable animationDrawable = (AnimationDrawable) load_imageview.getBackground();
        animationDrawable.start();

        /* 将显示Dialog的方法封装在这里面 */
        Window window = loadingDialog.getWindow();
        //覆盖状态栏
        window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL);
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        return loadingDialog;
    }

    public static void dismissLoadingDialog(Activity activity) {
        String key = getKey(activity);
        Dialog dialog = dialogs.remove(key);
        dismissDialogSafe(dialog);
        dialog = null;
    }

    private static void dismissDialogSafe(Dialog targetDialog) {
        if (targetDialog == null)
            return;
        if (!targetDialog.isShowing())
            return;
        //get the Context object that was used to create the dialog
        Context context = ((ContextWrapper) targetDialog.getContext()).getBaseContext();
        // if the Context used here was an activity AND it hasn't been finished or destroyed
        // then dismiss it
        if (context instanceof Activity) {
            if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed()) {
                dismissWithExceptionHandling(targetDialog);
            }
        } else {
            // if the Context used wasn't an Activity, then dismiss it too
            dismissWithExceptionHandling(targetDialog);
        }
    }

    private static void dismissWithExceptionHandling(Dialog dialog) {
        try {
            dialog.dismiss();
        } catch (final IllegalArgumentException e) {
            // Do nothing.
        } catch (final Exception e) {
            // Do nothing.
        }
    }


}
